package frame.project;

import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Main extends Activity {
	Button btnCamera,btnSetting,btnAlbum, btnEditPhoto, btnImport, btnAll, btn;
	HorizontalScrollView scroll;
	LinearLayout layoutScroll, layout;
	ProgressDialog dialog;

	DBAdapter db = new DBAdapter(this);
	long maxDate = 0,date;
	Bundle bundle;
	
	// Collection of images number in each label
	int[] labelCount = new int[7];
	
	// Collection of color names
	String[] labelColor = {"Red", "Orange", "Yellow", "Green", "Blue", "Pink", "Purple"};
	
	/**
	 * Check if any of the labels are currently being used.
	 * For example, if red label has one or more picture labeled with it, then increase counter
	 * @author Marcel
	 */
	public void checkLabel(){
		String label = null;
		
		db.open();
		Cursor c = db.getPath();
		c.moveToFirst();
			
		for (int x = 0; x < c.getCount(); x++){
			label = c.getString(3).toString();
			
			for (int y = 0; y < labelColor.length; y++){
				if (labelColor[y].equals(label)){
					labelCount[y] ++;
					break;
				}
			}
			
			c.moveToNext();
		}
		
		db.close();
		
		String text = "";
		for (int x = 0; x < labelColor.length; x++){
			text += Integer.toString(labelCount[x]) + ",";
		}
		addButtons();
		
	}
	
	/**
	 * If any of the counters are more than 0, create a new layout with a button inside it
	 * @author Marcel
	 */
	public void addButtons(){
		Resources r = getResources();
		float h = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, r.getDisplayMetrics());
		float w = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics());
		
		int height = Math.round(h);
		int width = Math.round(w);
		
		layoutScroll = (LinearLayout) findViewById(R.id.scrollAlbum);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
		params.setMargins(20, 0, 20, 0);
		
		for (int x = 0; x < labelCount.length; x++){
			if (labelCount[x] > 0){
				layout = new LinearLayout(this);
				layout.setLayoutParams(params);
				
				btn = new Button(this);
				btn.setHeight(height);
				btn.setWidth(width);
				btn.setOnClickListener(new ListenerAlbumBtn(labelColor[x]));
				
				layout.addView(btn);
				layoutScroll.addView(layout);
			}
		}
		
	}
	
	/**
	 * Check if the current image object's date modified is bigger than the latest date modified,
	 * means that the image is a new image. thus, add to database
	 * @param image - ImageDetails object, which stores image's path and date modified
	 * @author Marcel
	 */
    public void insertPath(ImageDetails image){
    	String path = image.getPath();
    	long date = image.getDate();
    	
    	if (date > maxDate){
    		db.open();
    		// Stores as a string, to prevent out of bound
    		db.insertPath(path, Long.toString(date), "Neutral", "Description..");
    		db.close();
    	}
    }
    
    /**
     * Check the latest date modified as a comparator for importing new images
     * @author Marcel
     * 
     */
    public void getMaxDate(){
    		db.open();
        	Cursor c = db.getPath();
        	c.moveToFirst();
        	if (c.getCount() > 0){
        		maxDate = Long.parseLong(c.getString(2));
        	}else{
        		maxDate = 0;
        	}
        	db.close();
    }
    
    /**
     * ImageDetails object, stores image's path and image's date modified
     * @author Marcel
     *
     */
    public class ImageDetails{
    	String path;
    	long date;
    	
    	public ImageDetails(String path, long date){
    		this.path = path;
    		this.date = date;
    	}
    	
    	public String getPath(){
    		return this.path;
    	}
    	
    	public long getDate(){
    		return this.date;
    	}
    }
    
    /**
     * Thread used to import images
     * Runs in background 
     * Shows loading indicator
     * @author Marcel, Jourdan
     *
     */
	class Imports extends AsyncTask<Object, Integer , Object> {
	    /**
	     * Load images from SD Card in the background
	     *  
	     * @see android.os.AsyncTask#doInBackground(Params[])
	     */
		@SuppressWarnings("deprecation")
		@Override
	    protected void onPreExecute() {
	        super.onPreExecute();
	        showDialog(0);
	    }
		
	    protected Object doInBackground(Object... params) {
	    	getMaxDate();
	    	
	        // Set up an array of the Title Image ID column we want
	        String[] mProjection = {
	        		MediaStore.Images.ImageColumns._ID,
	        		MediaStore.Images.ImageColumns.DATA,
	        		MediaStore.Images.ImageColumns.DATE_MODIFIED};
	        // Create the cursor pointing to the SDCard
	        @SuppressWarnings("deprecation")
			Cursor cursor = managedQuery( 
	        		MediaStore.Images.Media.EXTERNAL_CONTENT_URI,	//The URI of the content provider to query
	                mProjection,									//List of columns to return
	                null,											//SQL WHERE clause
	                null,											//The arguments to selection, if any ?s are pesent
	                null);											//SQL ORDER BY clause
	        
	        int indexPath = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA);
	        int indexDate = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATE_MODIFIED);
	        
	        int size = cursor.getCount();

	        String imagePath = "";
	        long imageDate = 0;
	        ImageDetails image;
	        
	        for (int i = 0; i < size; i++) {
	            // Move to next cursor
	            cursor.moveToPosition(i);
	            
	        	// Gets image's path
	            imagePath = cursor.getString(indexPath);
	            
	            // Gets image's date modified
	            imageDate = cursor.getLong(indexDate);
	            
	            // Stores in ImageDetails object
	            image = new ImageDetails(imagePath, imageDate);
	            
	            // Insert ImageDetails object to database
	            insertPath(image);
	            publishProgress((int) i / 100);
	            
	        }
	        return null;
	    }
	    /**
	     * If we have finished storing each item, increase the loading indicator
	     * @param value - percentage of finished item 
	     */
	    @Override
	    public void onProgressUpdate(Integer... value) {
	    	dialog.setProgress(value[value.length - 1]);
	    }
	    
	    /**
	     * Called once all the task has been done
	     * Close loading dialog indicator
	     */
	    @Override
	    protected void onPostExecute(Object result) {
	    	dismissDialog(0);
	    }
	}

	/**
	 * Listener class for each button generated dynamically through addButtons() method
	 * Opens album, containing only the images that are labeled with that label
	 * @author Marcel
	 *
	 */
	public class ListenerAlbumBtn implements View.OnClickListener{
		String color;
		
		public ListenerAlbumBtn(String color){
			this.color = color;
		}
		
		public void onClick(View v) {
			Intent intent = new Intent(getApplicationContext(), AlbumCustom.class);
			Bundle bundle = new Bundle();
			bundle.putString("color", color);
			intent.putExtras(bundle);
			startActivity(intent);
		}
		
	}

	/**
	 * OnCreate dialog for progress dialog box 
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case 0:
	        dialog = new ProgressDialog(this);
	        
	        dialog.setMessage("Downloading file. Please wait...");
	        dialog.setIndeterminate(false);
	        
	        // Sets max percentage
	        dialog.setMax(100);
	        
	        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	        dialog.setCancelable(false);
	        
	        // Shows the progress dialog box
	        dialog.show();
	        return dialog;
	    default:
	        return null;
	    }
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);
	
	    btnCamera = (Button) findViewById(R.id.btnCamera);
	    btnSetting = (Button) findViewById(R.id.btnSetting);
	    btnAlbum = (Button) findViewById(R.id.btnGallery);
	    btnEditPhoto = (Button) findViewById(R.id.btnEditPhoto);
	    btnImport = (Button) findViewById(R.id.btnImport);
	    btnAll = (Button) findViewById(R.id.btnAll);
	    
	    //activate camera feature
	    //opens camera class
	    btnCamera.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), Camera.class);
				startActivity(i);
			}
		});
	    
	    //activate setting
	    //opens setting class
	    btnSetting.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(),Setting.class);
				startActivity(i);
			}
		});
	    
	    //activate album feature
	    //opens album class
	    btnAlbum.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(),AlbumCustom.class);
				startActivity(i);
				checkLabel();
			}
		});
	    
	    //activate edit picture feature
	    //opens EditPicture class
	    btnEditPhoto.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), Edit.class);
				startActivity(i);
			}
		});
	    
	    //activate import feature
	    //opens Import class
	    btnImport.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				new Imports().execute();
			}
		});
	    
	    btnAll.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), AlbumCustom.class);
				startActivity(i);
			}
		});
	
	    checkLabel();
	}
	
	/*
	public void reload() {

	    Intent intent = getIntent();
	    overridePendingTransition(0, 0);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
	    finish();

	    overridePendingTransition(0, 0);
	    startActivity(intent);
	}*/
  }
